var mongoose = require('mongoose');
var Product = require('../models/product.model');

exports.create = function(req,res,next){
    const product = new Product(req.body); // req.body
    product.save(function (err,data) {
        if (err) {
          console.log(err);
        } else {
          res.json(data);
        }
    });
}

exports.update = function(req,res,next){
    const id = mongoose.Types.ObjectId(req.params.id);
    // 从Product这个数据模型里去找ID的对象并且将它进行更新操作
    Product.findByIdAndUpdate(id, {$set: req.body},{new:false})
    .then(data=>{
        // 这个data数据返回的是没有修改之前的数据
        res.json(data);
    })
}

exports.remove = function(req,res,next){
    const id = req.params.id;
    // 从Product这个数据模型里去找ID的对象并且将它进行更新操作
    Product.findByIdAndRemove(id, function(err,data){
        res.json({"message":"delete ok"});
    })
}

exports.removes = function (req, res, next) {
    var ids = req.body.ids;
    if (ids.length > 0){
        Product.remove({_id: {$in:ids} }).then(data=>{
            res.json({ "message": "deletes ok" });
        })
    }
}

exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page: 1;
    var limit = (req.body.limit) ? req.body.limit: 4;
    // 查询条件
    var queryCondition = {};
    // ID分类匹配
    if (req.body.cateId && req.body.cateId.trim().length > 0) {
        cateId = req.body.cateId;
        queryCondition = {
            cateId: cateId
        }
    }

    //正则匹配
    if (req.body.title && req.body.title.trim().length>0){
        title = req.body.title;
        // Object.assign 是对象合并。能实现多条件查询
        //将之前的queryCondition合并到后面的正则表达式里
        queryCondition = Object.assign(queryCondition,{
            "title": new RegExp(title,"i")
        })
    }
    
    Product.paginate(queryCondition, { page: page, limit: limit }, function (err, results) {
        res.json(results)
    })
}